package com.yunxin.core.utils.infra.utils;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zero°
 * @since 2023-06-17
 */
@Slf4j
public enum BeanCopierUtils {
    /**
     * 实例
     */
    X;

    /**
     * 类属性转为Map
     *
     * @param object object
     * @return Map<String, Object>
     */
    public Map<String, Object> convertClassToMap(Object object) {
        if (object == null) {
            return Collections.emptyMap();
        }
        Class clazz = object.getClass();
        Map<String, Object> map = new HashMap<>();
        try {
            //向上循环  遍历父类
            for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
                Field[] field = clazz.getDeclaredFields();
                for (Field f : field) {
                    f.setAccessible(true);
                    if (f.get(object) != null) {
                        map.put(f.getName(), f.get(object));
                    }
                }
            }
        } catch (IllegalAccessException e) {
            log.warn("反射失败", e);
        }
        return map;
    }

}
